FlashAir IoT Hub API usage example(server-side Web application)

Latest update: April 2018

Overview

In this tutorial, we will explain the server side web application using the FlashAir IoT Hub API with sample code. Please also refer to API usage.
In the FlashAir IoT Hub API, multiple access authorization methods are prepared according to application usage forms. This tutorial will explain about server-side web app among them.


Server side web application

The server side Web application is one with the following configuration.

  • The Web application is executed on the Web server.
  • Access the FlashAir IoT Hub API from the Web application.
  • Load the resources (HTML, CSS, JavaScript, etc.) from the Web application into the browser of the application user and execute it.
Configure server side web application

To use the FlashAir IoT Hub API with an application with such a configuration, select server side web application as the type of application and make application registration.

Premise

This tutorial is explained with the following assumptions.

  • Account registration of FlashAir IoT Hub has been completed.
  • You have app registration as the type of application as "Server-side Web application".
  • A Web server that can use PHP (5.2 or higher) is prepared.

Create sample code

As an example of using the API from the server side web application, access permission is done, and sample code for acquiring measured values is created in PHP.

Structure of sample code
  1. const.php
    Define constants to be used for the whole application such as the client ID of the application.
  2. main.php
    This page is displayed first. Display the request URL for access authorization as a link.
  3. auth.php
    This page is redirected after access authorization. Acquire the access token based on the authorization code.
  4. measurement.php
    Measurement API is used to acquire and display measured values.

const.php

<?php
define('CLIENT_ID', 'xxxxxxxxxxxxxxxxxxxxxx');
define('CLIENT_STATE', 'r5h2dcvm');
define('DEVICE_ID', '000000000000000000');
define('REDIRECT_URL', 'http://localhost/auth.php');
?>
  • Line 2:
    Client ID. Change to the ID issued after application registration.
  • Line 3:
    A random number character string for CSRF countermeasure specified by the client. Although it is set as a fixed value for explanation, in real applications, let's generate a new random number every time it gains access authorization.
  • Line 4:
    Device ID. When acquiring measurement values registered with this sample application with Measurement API , specify this device ID.
    Register FlashAir on FlashAir IoT Hub and change to FlashAir ID displayed when connecting.
  • Line 5:
    Redirect URL. For localhost please specify the URL of the server where auth.php is located.

main.php

<?php
require_once './const.php';

$api_url = 'https://iot-hub-api.flashair-developers.com/v1/authorize';
$responseType = 'code';
$clientId = CLIENT_ID;
$redirectUri = str_replace('.', '%2E', rawurlencode(REDIRECT_URL));
$scope = str_replace('.', '%2E', rawurlencode('user.read flashair.read flashair.write'));
$state = CLIENT_STATE;
$auth_url = "$api_url?response_type=$responseType&client_id=$clientId&redirect_uri=$redirectUri&state=$state&scope=$scope";
?>
<html>
  <body>
    <ul>
      <li><a href="<?php echo $auth_url ?>">Authorize</a></li>
    </ul>
  </body>
</html>

auth.php

<?php
require_once './const.php';

function authorization($clientId, $code, &$message) {
    if (empty($code)) {
        $message = 'Code was not returned.';
        return false;
    } else {
        $url = 'https://iot-hub-api.flashair-developers.com/v1/token';
        $data = array(
          'grant_type' => 'authorization_code',
          'code' => $code,
          'client_id' => $clientId,
          'redirect_uri' => REDIRECT_URL);
        $header = array('Content-Type: application/x-www-form-urlencoded');
        $curl=curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);

        $response = curl_exec($curl);
        curl_close($curl);
        if (empty($response)) {
            $message = 'Failed token api.';
            return false;
        }
        $response_json = json_decode($response);
        if (!$response_json) {
            $message = 'Failed decode token api:' . $response;
            return false;
        }
        if (property_exists($response_json, 'error')) {
            $message = 'Failed error occurred. ' . $response_json->error;
            return false;
        }
        if (!property_exists($response_json, 'access_token')) {
            $message = 'Failed decode access_token. token:' . $response_json;
            return false;
        }
        $access_token = $response_json->access_token;
        if (empty($access_token)) {
            $message = 'Failed decode access_token. token:' . $response_json;
            return false;
        }
        if (!file_put_contents('token.txt', $access_token)) {
            $message = 'Failed save authorization code.';
            return false;
        }
        $message = 'Authorization succeeded.';
        return true;
    }
}
$code = $_GET['code'];
$state = $_GET['state'];
$error = $_GET['error'];
$message = '';
$isAuthorized = false;

if (empty($state) || ($state != CLIENT_STATE)) {
    $message = 'state is invalid.';
} else if (!empty($error)) {
    $message = $error;
} else {
    $isAuthorized = authorization(CLIENT_ID, $code, $message);
}
?>
<html>
  <body>
    <p><?php echo $message ?></p>
    <?php if ($isAuthorized) : ?>
      <a href="measurement.php">Show Measurement Data</a>
    <?php endif; ?>
  </body>
</html>
  • Line 9:
    It is the URL of token issuance .
  • Lines 10-14:
    Generate parameters of token issuance .
    In the parameter code, specify the value of the acquired authorization code.
  • Lines 16-26:
    Send an HTTP request to the URL of token issuance generated on lines 10-14.
  • Lines 27-49:
    Retrieve the value of the access token from the response of token issuance , It saves in a text file token.txt.
  • Lines 57-59:
    We obtain authorization code ( code), client specified CSRF countermeasure random number character string ( state), error code ( error) from URL parameter.
  • Lines 74-76:
    If token issuance is successful, display the link of the measurement value display page ( measurement.php).

measurement.php

<?php
require_once './const.php';

function getMeasurements($token, $device_id, &$message) {
    $url = "https://iot-hub-api.flashair-developers.com/v1/flashairs/$device_id/measurements/flashair";
    $header = array("Authorization: Bearer $token");

    $curl=curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $header);

    $response = curl_exec($curl);
    curl_close($curl);

    if (empty($response)) {
        $message  = 'failed obtain response';
        return false;
    }
    $response_json = json_decode($response);
    if (empty($response_json)
        || !property_exists($response_json, 'measurements')) {
        $message  = 'failed obtain Mesurements';
        return false;
    }
    $measurements = $response_json->measurements;
    return $measurements;
}
$token = file_get_contents('token.txt', false, null);
$message = '';
$measurements = getMeasurements($token, DEVICE_ID, $message);
?>
<html>
  <body>
    <?php echo $message ?>
    <ul>
    <?php
    foreach ((array) $measurements as $measure) {
      $values = implode(', ', array_filter($measure->values, 'strlen'));
      echo '<li>' . $measure->time . ':' . $values . '</li>';
    }
    ?>
    </ul>
    <a href="main.php">Back</a>
  </body>
</html>
  • Line 5:
    This is the URL of Measurement API to acquire measurement value.
  • Line 6:
    For user token authentication , the value of the access token is specified in the HTTP request header.
  • Lines 8-16:
    Send an HTTP request to the URL of Measurement API .
  • Lines 18-28:
    Measurement value is acquired from the response of Measurement API .
  • Line 33:
    The value of the access token acquired and saved in auth.php is acquired from the text file token.txt.
  • Lines 40-43:
    The obtained measured value is output.

Execution of sample code

Let's actually run the sample code. Place the sample code in the root directory of the web server and start the web server.
Next, please access http://localhost/main.php from the browser.

Authorization request screen

Click on the Authorization link, you will be taken to the login screen.

Login screen

After entering your email address and password and logging in you will be prompted for access, please click the approval button.

Authorization screen

It will be redirected to http://localhost/auth.php.

Token issue screen

Click the Show Measurement Data link to display the http://localhost/measurement.php page.

Measurement acquisition screen

Measurement values are displayed on the page. If nothing is displayed, there is a possibility that measurement values are not registered in FlashAir IoT Hub. Execute the sample script and register measured values.

Conclusion

Access authorization of FlashAir IoT Hub API was performed, and measurement value data was acquired.

In this sample code, the access token is saved in a text file, but in actual use it should be saved in a location that can not be accessed by the application user, encryption etc. Please be careful.

Download sample code

iothub_tutorial_07.zip (3KB)

All sample code on this page is licensed under BSD 2-Clause License.